package com.hikw.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.MessageFormat;
import java.util.List;

/**
 * @Description: 服务信息
 * @ClassNmae: ServiceInformation
 * @Author: HeYue
 * @DateTime: 2021-07-13 23:53
 **/
@RestController
public class ServiceInformation {

    @Autowired
    private DiscoveryClient discoveryClient;

    @Value("${spring.application.name}")
    private String applicationName;


    @GetMapping("/service/serviceInfo")
    public Object serviceInfo() {
        int count = 1;
        List<String> services = discoveryClient.getServices();
        System.out.println(MessageFormat.format("服务总数:{0}", services.size()));
        List<ServiceInstance> instances = discoveryClient.getInstances(applicationName);
        for (ServiceInstance instance : instances) {
            System.out.println("*-----------------------------------------*");
            System.out.println(MessageFormat.format("序号:{0}\n主机名:{1}\n端口号:{2}\nURI:{3}\n服务ID:{4}",
                    count++,
                    instance.getHost(),
                    instance.getPort(),
                    instance.getUri(), instance.getServiceId()));
            System.out.println("*-----------------------------------------*");
        }
        return this.discoveryClient;
    }
}
